package repository;

import java.sql.*;

import static repository.QueryDAO.getCurrentBalance;

/**
 * @description:
 * @Author Felix Torn
 * @create: 2023-12-24 19:37
 **/
public class UpdateDAO {
    // 更新余额
    public static boolean updateBalance(double amount) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            // 获取当前余额
            double currentBalance = getCurrentBalance();

            // 计算新余额
            double newBalance = currentBalance + amount;

            // 获取数据库连接
            connection = DatabaseConnector.getConnection();
            assert connection != null;

            // 开启事务
            connection.setAutoCommit(false);

            // 插入新的余额记录
            String updateQuery = "INSERT INTO balances (amount, datetime) VALUES (?, NOW())";
            preparedStatement = connection.prepareStatement(updateQuery);
            preparedStatement.setDouble(1, newBalance);
            preparedStatement.executeUpdate();

            // 提交事务
            connection.commit();
            return true;
        } catch (SQLException e) {
            // 事务回滚
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            // 关闭资源
            DatabaseConnector.closePreparedStatement(preparedStatement);
            DatabaseConnector.closeConnection(connection);
        }
    }



}
